package com.diorsunion.hedge.client.ui;

import com.diorsunion.hedge.common.ConnectionStatus;
import com.diorsunion.hedge.common.ServiceResult;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.function.Function;

/**
 * 连接对话框，包括连接服务器，连接券商客户端等
 * @author wangnima
 */
public class ConnectDlg extends JDialog  {

    final JTextField m_ipAddress	;
    final JTextField 	m_port;
    final JButton 	m_ok  = new JButton("连接");;
    JButton 	m_cancel = new JButton( "关闭窗口");
    boolean 	m_rc = false; //是否连接
    Function<InetSocketAddress,Boolean> doConnectFunction ;

    ConnectDlg(String name,String defaultAddress,int defaultPort,Function<InetSocketAddress,Boolean> doConnectFunction){
        this.doConnectFunction = doConnectFunction;
        m_ipAddress = new JTextField(defaultAddress);
        m_port = new JTextField(String.valueOf(defaultPort));
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(m_ok);
        buttonPanel.add(m_cancel);
        m_ok.addActionListener(x -> onOk());
        m_cancel.addActionListener(x -> onCancel());
        JPanel midPanel = new JPanel();
        midPanel.setLayout( new GridLayout( 0, 1, 5, 5) );
        midPanel.add(new JLabel(name+"地址"));
        midPanel.add( m_ipAddress);
        midPanel.add( new JLabel( name+"端口号") );
        midPanel.add( m_port);
        getContentPane().add(midPanel, BorderLayout.CENTER);
        getContentPane().add( buttonPanel, BorderLayout.SOUTH);
        setLocationRelativeTo(null);
        setTitle(name);
        pack();
    }

    void onOk() {
        m_rc = false;
        if(!StringUtils.isEmpty(m_ipAddress.getText()) && !StringUtils.isEmpty(m_port.getText())){
            String address = m_ipAddress.getText() ;
            int port = Integer.parseInt( m_port.getText());
            m_rc = true;
            setVisible(false);
            InetSocketAddress socketAddress = new InetSocketAddress(address,port);
            boolean b = false;
            Throwable error = null;
            try{
                b =  doConnectFunction.apply(socketAddress);
            }catch (Throwable e){
                error = e;
            }
            if(b){
                JOptionPane.showMessageDialog(this, "连接服务器成功", "连接提示", JOptionPane.INFORMATION_MESSAGE);
            }else {
                JOptionPane.showMessageDialog(this, error==null?"未知异常":error.getMessage(), "连接服务器失败", JOptionPane.WARNING_MESSAGE);
            }
        }else{
            JOptionPane.showMessageDialog(this, "连接服务器失败", "连接提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    void onCancel() {
        m_rc = false;
        setVisible(false);
    }
}
